
var students = null;
var formMode = 'add';

$.ajaxSetup({
  contentType: "application/json"
});

$(function () {
  $.getJSON('/students', function (data) {
    students = data.data;
    for (var i = 0; i < students.length; i++) {
      var student = students[i];

      var row = $('<tr>').attr('student-no', student.studentNo);
      if (student.gender == '女') {
        row.addClass('female');
      }
      var tdStunNo = $('<td>').text(student.studentNo);
      var tdName = $('<td>').text(student.name);
      var tdClass = $('<td>').text(student.class);
      var tdGender = $('<td>').text(student.gender);
      var btnDelete = $('<button>').text('删除').on('click', function (e) {
        var studentNo = $(e.target).parents('tr').attr('student-no');
        deleteStudent(studentNo);
      });

      var btnUpdate = $('<a>').text('修改').on('click', function (e) {
        var studentNo = $(e.target).parents('tr').attr('student-no');
        updateStudent(studentNo);
      });
      var tdOperation = $('<td>').append(btnDelete, btnUpdate);
      row.append(tdStunNo, tdName, tdClass, tdGender, tdOperation);
      $('tbody').append(row);
    }
  })
  $('form').on('submit', function (e) {
    e.preventDefault();
  });

  $('#btnSave').on('click', function () {
    var newStudent = {};
    newStudent.studentNo = $('#iptStudentNo').val();
    newStudent.name = $('#iptName').val();
    newStudent.class = $('#sltClass').val();
    newStudent.gender = $('input[name="gender"]:checked').val();

    if(formMode == 'add') {
      $.post('/students/add', JSON.stringify(newStudent), function (data) {
        if (data.message == 'success') {
          // 添加学生成功，重新加载学生数据，并渲染表格
          alert('添加学生成功');
          resetForm();
        }
      })
    } else if(formMode == 'edit') {
      $.post('/students/edit', JSON.stringify(newStudent), function (data) {
        if (data.message == 'success') {
          // 添加学生成功，重新加载学生数据，并渲染表格
          alert('修改学生成功');
          resetForm();
        }
      })
    }
    
  })

  $('#btnReset').on('click', resetForm)
})

function deleteStudent(studentNo) {
  const api = '/students/delete?studentNo=' + studentNo;
  $.getJSON(api, function (data) {
    if (data.message == 'success') {
      // 刷新学生表格
      alert('删除学生成功');
    }
  })
}

/**
 * 在表单上显示要修改的学生信息
 * @param {*} studentNo 
 */
function updateStudent(studentNo) {
  var student = students.find(function (s) {
    if (s.studentNo == studentNo) {
      return true;
    }
  })
  $('#iptStudentNo').val(student.studentNo);
  $('#iptName').val(student.name);
  $('#sltClass').val(student.class);
  $('input[value=' + student.gender + ']').prop('checked', true);
  formMode = 'edit';
}

/**
 * 重置表单
 * 完成：1、formMode设置为add，2、将输入框中的值全部清除
 */
function resetForm(){
  formMode="add";
  $('#iptStudentNo').val(null);
  $('#iptName').val(null);
  $('#sltClass').val(null);
  $('input[name=gender]').prop('checked', false);
}
